package core.net.protocol;

import core.buffer.Buffer;
import core.buffer.BufferManager;

import java.util.function.Consumer;

public class Packet {

    public static final byte PACK_SIZE = 1;
    public static final byte MAX_PACK_LEN = 127;

    private Buffer _buffer;
    private BufferManager _bufferManager;
    public Packet(BufferManager bufferManager) {
        _bufferManager = bufferManager;
    }

    public void unpack(Buffer readBuffer, Consumer<Buffer> handle) {
        while (readBuffer.readRemaining() > 0) {
            if (_buffer == null) {
                _buffer = _bufferManager.apply(readBuffer.read());
            }
            Buffer.fill(readBuffer, _buffer);
            if (_buffer.writeRemaining() == 0) {
                handle.accept(_buffer);
                _buffer = null;
            }
        }
    }

    public void dispose() {
        if (_buffer != null) _buffer.clear();
        if (_bufferManager != null) _bufferManager = null;
    }
}
